
package com.oahcfly.chgame.core.mvc;

import java.util.HashMap;

import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.utils.Array;
import com.oahcfly.chgame.core.helper.CHFileHelper;

/** 场景过渡Loading界面用于资源的预加载
 * 
 * @author haocao */
public abstract class CHBaseLoadingScreen extends CHScreen {

	private CHScreen nextChScreen;

	public void setNextScreen (CHScreen nextScreen) {
		this.nextChScreen = nextScreen;
	}

	/** @param fileDirectory 资源所在目录 */
	public void addAssets (String fileDirectory) {
		FileHandle[] fileHandles = CHFileHelper.getFileHandles(fileDirectory);
		for (FileHandle fileHandle : fileHandles) {
			String path = fileHandle.path();
			if (path.endsWith(".png") || path.endsWith(".jpg")) {
				addAsset(path, Texture.class);
			}
		}
	}

	public <T> void addAsset (String path, Class<T> type) {
		Array<String> usedTextureArray = nextChScreen.getUsedTextureArray();
		if (usedTextureArray == null) {
			usedTextureArray = new Array<String>();
			nextChScreen.setUsedTextureArray(usedTextureArray);
		}

		boolean loaded = getGame().getAssetManager().isLoaded(path);
		if (!loaded) {
			getGame().getAssetManager().load(path, type);
			usedTextureArray.add(path);
		}
	}

	private float delaytime = 0;

	@Override
	public void act (float delta) {
		// TODO Auto-generated method stub
		super.act(delta);

		boolean loaded = getGame().getAssetManager().update();
		loadingAssets(getGame().getAssetManager().getProgress());
		if (loaded) {
			delaytime += delta;
		}
		if (delaytime > 0.3f) {
			delaytime = 0;
			getGame().setScreen(nextChScreen);
		}

	}

	public abstract void loadingAssets (float progress);

	@Override
	public void handleUIEvent (String key, HashMap<String, String> data) {
		// TODO Auto-generated method stub

	}

	public CHScreen getNextCHScreen () {
		return nextChScreen;
	}

}
